package OpenService

import (
	"database/sql"
	"gdshop-admin-go-api/app/entity"
	"gdshop-admin-go-api/app/request/OpenReq"
	"gdshop-admin-go-api/app/response/OpenResp"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"gdshop-admin-go-api/library/tools/jwt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
)

func Login(r *ghttp.Request, parames *OpenReq.Login) *response.JsonResponse {
	// 校验 验证码
	/*if !myCaptcha.VerifyCaptcha(parames.CaptchaId, parames.VerifyCode) {
		return response.FailByRequestMessage(r, "验证码错误")
	}*/
	ctx := r.GetCtx()
	adminModel := (*entity.Admin)(nil)
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "admin").Where(
		"account = ?", parames.Username).Struct(&adminModel)
	if err != nil {
		if err == sql.ErrNoRows {
			return response.FailByRequestMessage(nil, "请输入正确的账号密码")
		}
		return response.FailByRequestMessage(r, err.Error())
	}

	// 判断密码是否正确
	if parames.Type == "hash" {
		if tools.EncryptPasswordHash(parames.Password, adminModel.PasswordSalt) != adminModel.Password {
			// 记录错误登陆日志，后面做封IP处理
			//fmt.Println("登录hash ", tools.EncryptPassword(parames.Password, memberModel.PasswordSalt))
			return response.FailByRequestMessage(nil, "请输入正确的账号密码")
		}
	} else {
		if tools.EncryptPassword(parames.Password, adminModel.PasswordSalt) != adminModel.Password {
			// 记录错误登陆日志，后面做封IP处理
			//fmt.Println("登录hash ", tools.EncryptPassword(parames.Password, memberModel.PasswordSalt))
			return response.FailByRequestMessage(nil, "请输入正确的账号密码")
		}
	}

	if adminModel.Status < 1 {
		return response.FailByRequestMessage(nil, "账号被禁用")
	}

	resp := new(OpenResp.Login)
	if err := gconv.Struct(adminModel, resp); err != nil {
		return response.FailByRequestMessage(nil, "数据转换失败")
	}

	tokenString, err := jwt.GenerateLoginToken(uint(adminModel.Id), adminModel.Realname)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	resp.Token = tokenString
	resp.RefreshToken = tokenString
	resp.RefreshExpire = 1296000
	resp.Expire = 1296000
	resp.UserInfo = &OpenResp.LoginUserInfo{
		UserId:       gconv.String(adminModel.Id),
		UserName:     adminModel.Account,
		Avatar:       adminModel.Avatar,
		AvatarPrefix: "",
		Role:         g.SliceStr{},
	}

	// 登录成功后，缓存当前用户的一些信息
	g.Redis().Do("HSET", "IsAdmin",
		adminModel.Id, adminModel.Account == "admin")

	return response.SuccessByRequestMessageData(nil, "成功", resp)
}
